#include "postgres.h"

#include "fmgr.h"
#include "hstore/hstore.h"
#include "plperl.h"
#include "plperl_helpers.h"

PG_MODULE_MAGIC;

extern void _PG_init(void);

/* 链接到 hstore 模块中的函数 */
typedef HStore *(*hstoreUpgrade_t) (Datum orig);
static hstoreUpgrade_t hstoreUpgrade_p;
typedef int (*hstoreUniquePairs_t) (Pairs *a, int32 l, int32 *buflen);
static hstoreUniquePairs_t hstoreUniquePairs_p;
typedef HStore *(*hstorePairs_t) (Pairs *pairs, int32 pcount, int32 buflen);
static hstorePairs_t hstorePairs_p;
typedef size_t (*hstoreCheckKeyLen_t) (size_t len);
static hstoreCheckKeyLen_t hstoreCheckKeyLen_p;
typedef size_t (*hstoreCheckValLen_t) (size_t len);
static hstoreCheckValLen_t hstoreCheckValLen_p;


/*
 * 模块初始化函数：获取跨模块调用的函数指针。
 */
void _PG_init(void)
{
	/* 断言验证上述 typedef 与原始声明匹配 */
	AssertVariableIsOfType(&hstoreUpgrade, hstoreUpgrade_t);
	hstoreUpgrade_p = (hstoreUpgrade_t)
		load_external_function("$libdir/hstore", "hstoreUpgrade",
							   true, NULL);
	AssertVariableIsOfType(&hstoreUniquePairs, hstoreUniquePairs_t);
	hstoreUniquePairs_p = (hstoreUniquePairs_t)
		load_external_function("$libdir/hstore", "hstoreUniquePairs",
							   true, NULL);
	AssertVariableIsOfType(&hstorePairs, hstorePairs_t);
	hstorePairs_p = (hstorePairs_t)
		load_external_function("$libdir/hstore", "hstorePairs",
							   true, NULL);
	AssertVariableIsOfType(&hstoreCheckKeyLen, hstoreCheckKeyLen_t);
	hstoreCheckKeyLen_p = (hstoreCheckKeyLen_t)
		load_external_function("$libdir/hstore", "hstoreCheckKeyLen",
							   true, NULL);
	AssertVariableIsOfType(&hstoreCheckValLen, hstoreCheckValLen_t);
	hstoreCheckValLen_p = (hstoreCheckValLen_t)
		load_external_function("$libdir/hstore", "hstoreCheckValLen",
							   true, NULL);
}


/* 这些定义必须在模块初始化函数之后 */
#define hstoreUpgrade hstoreUpgrade_p
#define hstoreUniquePairs hstoreUniquePairs_p
#define hstorePairs hstorePairs_p
#define hstoreCheckKeyLen hstoreCheckKeyLen_p
#define hstoreCheckValLen hstoreCheckValLen_p


PG_FUNCTION_INFO_V1(hstore_to_plperl);

Datum hstore_to_plperl(PG_FUNCTION_ARGS)
{
	dTHX;
	HStore	   *fc_in = PG_GETARG_HSTORE_P(0);
	int			fc_i;
	int			fc_count = HS_COUNT(fc_in);
	char	   *fc_base = STRPTR(fc_in);
	HEntry	   *fc_entries = ARRPTR(fc_in);
	HV		   *fc_hv;

	fc_hv = newHV();

	for (fc_i = 0; fc_i < fc_count; fc_i++)
	{
		const char *fc_key;
		SV		   *fc_value;

		fc_key = pnstrdup(HSTORE_KEY(fc_entries, fc_base, fc_i),
					   HSTORE_KEYLEN(fc_entries, fc_i));
		fc_value = HSTORE_VALISNULL(fc_entries, fc_i) ? newSV(0) :
			cstr2sv(pnstrdup(HSTORE_VAL(fc_entries, fc_base, fc_i),
							 HSTORE_VALLEN(fc_entries, fc_i)));

		(void) hv_store(fc_hv, fc_key, strlen(fc_key), fc_value, 0);
	}

	return PointerGetDatum(newRV((SV *) fc_hv));
}


PG_FUNCTION_INFO_V1(plperl_to_hstore);

Datum plperl_to_hstore(PG_FUNCTION_ARGS)
{
	dTHX;
	SV		   *fc_in = (SV *) PG_GETARG_POINTER(0);
	HV		   *fc_hv;
	HE		   *fc_he;
	int32		fc_buflen;
	int32		fc_i;
	int32		fc_pcount;
	HStore	   *fc_out;
	Pairs	   *fc_pairs;

	/* 递归解引用引用。 */
	while (SvROK(fc_in))
		fc_in = SvRV(fc_in);

	/* 现在我们必须有一个哈希。 */
	if (SvTYPE(fc_in) != SVt_PVHV)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("cannot transform non-hash Perl value to hstore")));
	fc_hv = (HV *) fc_in;

	fc_pcount = hv_iterinit(fc_hv);

	fc_pairs = palloc(fc_pcount * sizeof(Pairs));

	fc_i = 0;
	while ((fc_he = hv_iternext(fc_hv)))
	{
		char	   *fc_key = sv2cstr(HeSVKEY_force(fc_he));
		SV		   *fc_value = HeVAL(fc_he);

		fc_pairs[fc_i].key = pstrdup(fc_key);
		fc_pairs[fc_i].keylen = hstoreCheckKeyLen(strlen(fc_pairs[fc_i].key));
		fc_pairs[fc_i].needfree = true;

		if (!SvOK(fc_value))
		{
			fc_pairs[fc_i].val = NULL;
			fc_pairs[fc_i].vallen = 0;
			fc_pairs[fc_i].isnull = true;
		}
		else
		{
			fc_pairs[fc_i].val = pstrdup(sv2cstr(fc_value));
			fc_pairs[fc_i].vallen = hstoreCheckValLen(strlen(fc_pairs[fc_i].val));
			fc_pairs[fc_i].isnull = false;
		}

		fc_i++;
	}

	fc_pcount = hstoreUniquePairs(fc_pairs, fc_pcount, &fc_buflen);
	fc_out = hstorePairs(fc_pairs, fc_pcount, fc_buflen);
	PG_RETURN_POINTER(fc_out);
}
